package com.yuanli.cosmeticmirror.view.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.AppCompatSeekBar;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.cgfay.filter.glfilter.color.bean.DynamicColor;
import com.cgfay.filter.glfilter.resource.FilterHelper;
import com.cgfay.filter.glfilter.resource.ResourceJsonCodec;
import com.comenjoysoft.baselibrary.util.ThreadUtils;
import com.jaygoo.widget.OnRangeChangedListener;
import com.jaygoo.widget.RangeSeekBar;
import com.jaygoo.widget.VerticalRangeSeekBar;
import com.kongzue.dialog.v3.CustomDialog;
import com.ljy.cameralibrary.camera.CameraParam;
import com.ljy.cameralibrary.renderer.RecordRenderer;
import com.ljy.cameralibrary.utils.BrightnessUtils;
import com.ljy.cameralibrary.widget.CameraGrid;
import com.ljy.cameralibrary.widget.CameraPhotoFrameView;
import com.ljy.cameralibrary.widget.GLRecordView;
import com.orhanobut.logger.Logger;
import com.rxjava.rxlife.RxLife;
import com.tbruyelle.rxpermissions2.RxPermissions;

import com.yuanli.cosmeticmirror.GirdLineLisenter;
import com.yuanli.cosmeticmirror.R;
import com.yuanli.cosmeticmirror.base.BaseActivity;
import com.yuanli.cosmeticmirror.base.Config;
import com.yuanli.cosmeticmirror.base.MyApp;
import com.yuanli.cosmeticmirror.bean.MemberInfoBean;
import com.yuanli.cosmeticmirror.event.MainEvent;
import com.yuanli.cosmeticmirror.model.iview.IMainView;
import com.yuanli.cosmeticmirror.persenter.MainPersenter;
import com.yuanli.cosmeticmirror.persenter.RecordPresenter;
import com.yuanli.cosmeticmirror.utils.BitmapUtils;
import com.yuanli.cosmeticmirror.utils.CameraHelp;
import com.yuanli.cosmeticmirror.utils.FileUtils;
import com.yuanli.cosmeticmirror.utils.RxTimer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.schedulers.Schedulers;

import static com.yuanli.cosmeticmirror.base.Constant.ACTION_START_FILTER_SWITCHING;
import static com.yuanli.cosmeticmirror.base.Constant.ACTION_START_PHOTO_FRAME_SWITCHING;


public class MainActivity extends BaseActivity implements GirdLineLisenter, IMainView {
    @BindView(R.id.gl_record_view)
    GLRecordView mGLRecordView;
    @BindView(R.id.camera_take_photo)
    ImageView cameraTakePhoto;
    @BindView(R.id.camera_adjust_brightness)
    ImageView cameraAdjustBrightness;
    @BindView(R.id.camera_adjust_ize)
    AppCompatSeekBar cameraAdjustIze;
    @BindView(R.id.camera_adjust_brightness_seekbar)
    VerticalRangeSeekBar cameraAdjustBrightnessSeekbar;
    @BindView(R.id.camera_adjust_size_ll)
    LinearLayout cameraAdjustSizeLl;
    @BindView(R.id.camera_line)
    CameraGrid cameraLine;
    @BindView(R.id.photo_frame)
    CameraPhotoFrameView photoFrame;
    @BindView(R.id.photo_view)
    FrameLayout photoView;
    @BindView(R.id.camera_photo_frame)
    ImageView cameraPhotoFrame;
    @BindView(R.id.camera_filter)
    ImageView cameraFilter;
    @BindView(R.id.camera_tutorial)
    ImageView cameraTutorial;
    @BindView(R.id.iv_hairstyle_btn)
    ImageView cameraMore;
    @BindView(R.id.camera_me)
    ImageView cameraMe;
    @BindView(R.id.bottom_layout)
    ConstraintLayout bottomLayout;
    @BindView(R.id.camera_music)
    ImageView cameraMusic;
    @BindView(R.id.music_text)
    TextView musicText;
    @BindView(R.id.iv_more_btn)
    ImageView ivMoreBtn;
    @BindView(R.id.tv_more)
    TextView tvMore;
    private RecordRenderer mRenderer;
    private RecordPresenter mPresenter;
    private CameraHelp mCameraHelp = new CameraHelp();
    private Bitmap bitmap;
    private boolean girdIsShow;
    private boolean fillLight;

    private long mLastClickTime = 0;
    public final long TIME_INTERVAL = 1000L;
    private MainPersenter persenter;

    private RxTimer rxTimer;

    private boolean isHide;

    @Override
    protected int getContentView() {
        //设置全屏显示
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        return R.layout.activity_main;
    }

    @Override
    protected void init(Bundle bundle) {
        EventBus.getDefault().register(this);
        mPresenter = new RecordPresenter(this);
        mRenderer = new RecordRenderer(mPresenter);
        mGLRecordView.setEGLContextClientVersion(3);
        mGLRecordView.setRenderer(mRenderer);
        mGLRecordView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
        persenter = new MainPersenter(this, this);
        rxTimer = new RxTimer();
    }

    @Override
    protected void initView() {
        viewVisible(View.GONE);
        cameraAdjustBrightnessSeekbar.setOnRangeChangedListener(new OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float leftValue, float rightValue, boolean isFromUser) {
                getScreenBrightness(leftValue / 100);
            }

            @Override
            public void onStartTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }

            @Override
            public void onStopTrackingTouch(RangeSeekBar view, boolean isLeft) {

            }
        });
        cameraAdjustIze.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (mGLRecordView != null) {
                    mPresenter.cameraZoomOut(progress / 10);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //        surfaceView.setOnTouchListener(this);
    }

    @Override
    protected void initData() {
        showLoadDialog();
        persenter.getVipInfo();
        ThreadUtils.executeByIo(new ThreadUtils.Task<Object>() {
            @Override
            public Object doInBackground() throws Throwable {
                FileUtils.createFolder(Config.PHOTO_PATH);
                FileUtils.createFolder(Config.MUSIC_PATH);
                return null;
            }

            @Override
            public void onSuccess(Object result) {

            }

            @Override
            public void onCancel() {

            }

            @Override
            public void onFail(Throwable t) {

            }
        });
    }



    /**
     * 加入调整亮度
     */
    private void getScreenBrightness(float i) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        //screenBrightness的值是0.0-1.0 从0到1.0 亮度逐渐增大 如果是-1，那就是跟随系统亮度 这里调成 0.78左右
        lp.screenBrightness = i;
        getWindow().setAttributes(lp);
    }

    public void takePicture() {
        CameraParam.getInstance().isTakePicture = true;
        mGLRecordView.requestRender();
    }


    private void viewVisible(int visible) {
        cameraMusic.setVisibility(visible);
        musicText.setVisibility(visible);
        ivMoreBtn.setVisibility(visible);
        tvMore.setVisibility(visible);
        bottomLayout.setVisibility(visible);
        cameraAdjustSizeLl.setVisibility(visible);
        cameraAdjustBrightness.setVisibility(visible);
        cameraAdjustBrightnessSeekbar.setVisibility(visible);
        cameraMe.setVisibility(visible);

    }

    @Override
    protected void onResume() {
        super.onResume();
        mGLRecordView.onResume();
        mPresenter.onResume();
        if (cameraAdjustBrightnessSeekbar.getProgressLeft() == 0) {
            cameraAdjustBrightnessSeekbar.setProgress(50);
        }
    }



    @Override
    protected void destroy() {
        if (mCameraHelp != null) {
            mCameraHelp.release();
        }
        if (rxTimer != null) {
            rxTimer.cancel();
        }
        mPresenter.release();
        mPresenter = null;
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMainEven(MainEvent event) {
        if (event.getAction() == ACTION_START_FILTER_SWITCHING) {
            int color = (int) event.getData();

            changeDynamicFilter(color);
        } else if (event.getAction() == ACTION_START_PHOTO_FRAME_SWITCHING) {

            bitmap = (Bitmap) event.getData();
            Logger.d("bitmap        " + bitmap);
            if (bitmap == null) {
                photoFrame.setZheZhao(false, null);
            }

            photoFrame.setZheZhao(true, bitmap);
        }
    }

    /**
     * 保存操作
     */

    public void saveData(Bitmap bitmap) {
        String s = "";
        photoFrame.setDrawingCacheEnabled(true);
        photoFrame.buildDrawingCache();
        Bitmap path = FileUtils.getBitmapByView(photoFrame);
        Bitmap mergeBitmap = FileUtils.mergeBitmap(bitmap, path);
        s = BitmapUtils.saveBitmapToMerge(FileUtils.getSDCardRoot() + Config.PHOTO_PATH, mergeBitmap);
        if (!TextUtils.isEmpty(s)) {
            startActivity(new Intent(MainActivity.this, PhotoInfoActivity.class).putExtra("saveBitmap", s));
        }
        isHide = false;
    }


    @OnClick({R.id.camera_take_photo, R.id.photo_view,
            R.id.camera_music, R.id.camera_photo_frame,
            R.id.camera_filter, R.id.camera_tutorial,
            R.id.iv_hairstyle_btn, R.id.camera_me, R.id.iv_more_btn})
    public void onViewClicked(View view) {
        long nowTime = System.currentTimeMillis();
        if (nowTime - mLastClickTime < TIME_INTERVAL) {
            // do something
            return;
        }
        mLastClickTime = nowTime;
        switch (view.getId()) {
            case R.id.camera_take_photo:
                isHide = true;
                takePicture();
                break;
            case R.id.photo_view:
                if (!isHide && cameraMusic.getVisibility() == View.GONE) {
                    viewVisible(View.VISIBLE);
                }
                if (rxTimer != null) {
                    rxTimer.cancel();
                    rxTimer.timer(5000, number -> {
                        viewVisible(View.GONE);
                    });
                }
                break;
            case R.id.camera_music:
                checkAppPermission();
                break;
            case R.id.camera_photo_frame:
                startActivity(new Intent(MainActivity.this, PhotoFrameActivity.class));
                break;
            case R.id.camera_filter:
                startActivity(new Intent(MainActivity.this, FilterActivity.class));
                break;
            case R.id.camera_tutorial:
                startActivity(new Intent(MainActivity.this, TutorialActivity.class));
                break;
            case R.id.iv_hairstyle_btn:
                openWxApplet();
                break;
            case R.id.iv_more_btn:
                getCustomDialog(this);
                break;
            case R.id.camera_me:
                startActivity(new Intent(MainActivity.this, UserInfoActivity.class));
                break;
            default:
                break;
        }
    }

    /**
     * 打开微信小程序
     */
    private void openWxApplet(){
        mPresenter.openWxApplet(this);
    }

    private void checkAppPermission() {
        new RxPermissions(this).request(Manifest.permission.INTERNET,
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribeOn(Schedulers.io())
                .as(RxLife.asOnMain(this))
                .subscribe(aBoolean -> {
                    if (aBoolean) {
                        startActivity(new Intent(MainActivity.this, MusicRingActivity.class));
                    } else {
                        showToast("请求权限失败");
                    }
                });
    }

    /**
     * 相机界面  更多
     *
     * @param girdLineLisenter
     * @return
     */
    private CustomDialog getCustomDialog(GirdLineLisenter girdLineLisenter) {
        return CustomDialog.show(MainActivity.this, R.layout.items_more, (dialog, v) -> {
            LinearLayout btnOk = v.findViewById(R.id.more_ll);
            AppCompatCheckBox moreCb = v.findViewById(R.id.more_cb);
            AppCompatCheckBox moreNightLight = v.findViewById(R.id.more_night_light);
            btnOk.setOnClickListener(v1 -> dialog.doDismiss());
            moreCb.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (!girdIsShow) {
                    girdIsShow = true;
                    buttonView.setChecked(true);
                } else {
                    girdIsShow = false;
                    buttonView.setChecked(false);
                }
                girdLineLisenter.onIsOpenGridLineLisenter(girdIsShow);
                dialog.doDismiss();
            });
            moreNightLight.setOnCheckedChangeListener((buttonView, isChecked) -> {
                if (!fillLight) {
                    fillLight = true;
                    buttonView.setChecked(true);
                } else {
                    fillLight = false;
                    buttonView.setChecked(false);
                }
                girdLineLisenter.onIsOpenFillLightLisenter(fillLight);
                dialog.doDismiss();
            });
        }).setCustomDialogStyleId(R.style.moreDialog).setAlign(CustomDialog.ALIGN.TOP).setFullScreen(true);
    }

    /**
     * 绑定相机输出的SurfaceTexture
     *
     * @param surfaceTexture
     */
    public void bindSurfaceTexture(@NonNull SurfaceTexture surfaceTexture) {
        mGLRecordView.queueEvent(() -> mRenderer.bindSurfaceTexture(surfaceTexture));
    }

    /**
     * 更新预览纹理大小
     *
     * @param width
     * @param height
     */
    public void updateTextureSize(int width, int height) {
        if (mRenderer != null) {
            mRenderer.setTextureSize(width, height);
        }
    }

    /**
     * 刷新画面
     */
    public void onFrameAvailable() {
        CameraParam.getInstance().isTakePicture = false;
        if (mGLRecordView != null) {
            mGLRecordView.requestRender();
        }
    }

    /**
     * 切换动态滤镜
     *
     * @param filterIndex
     */
    public void changeDynamicFilter(int filterIndex) {
        if (mGLRecordView != null) {
            mGLRecordView.queueEvent(() -> {
                String folderPath = FilterHelper.getFilterDirectory(this) + File.separator +
                        FilterHelper.getFilterList().get(filterIndex).unzipFolder;
                DynamicColor color = null;
                if (!"none".equalsIgnoreCase(FilterHelper.getFilterList().get(filterIndex).unzipFolder)) {
                    try {
                        color = ResourceJsonCodec.decodeFilterData(folderPath);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                mRenderer.changeDynamicFilter(MainActivity.this, color);
            });
        }
    }

    /**
     * 切换动态滤镜
     */
    public void changeDynamicFilter(DynamicColor color) {
        if (mGLRecordView != null) {
            mGLRecordView.queueEvent(() -> {
                mRenderer.changeDynamicFilter(MainActivity.this, color);
            });
        }
    }

    @Override
    public void onIsOpenGridLineLisenter(boolean girdIsShow) {
        cameraLine.setShowGrid(girdIsShow);

    }

    @Override
    public void onIsOpenFillLightLisenter(boolean isOpen) {
        BrightnessUtils.setWindowBrightness(MainActivity.this, isOpen
                ? BrightnessUtils.MAX_BRIGHTNESS : CameraParam.getInstance().brightness);
    }

    @Override
    public void onVipSucess(MemberInfoBean object) {
        dialogDismiss();
        MyApp.IsVIP = object != null && object.getDay() > 0;
    }


    private long mill;
    @Override
    public void onBackPressed() {
        boolean isExit = SystemClock.elapsedRealtime() - mill <= 2000;
        mill = SystemClock.elapsedRealtime();
        if (isExit){
            appManager.AppExit(this);
        }else{
            showToast("再次点击退出程序");
        }
    }
}
